<script lang="ts" setup>
import { deletePictureUsingPost } from '@/api/tupianmokuai';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router'

interface Props {
  dataList?: API.PictureVO[]
  loading?: boolean
  showOp?: boolean
  onReload?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  dataList: () => [],
  loading: false,
  showOp: false,
})

// 处理点击跳转
const router = useRouter()
// 跳转至图片详情
const handleClickPicture = (picture: API.PictureVO) => {
  router.push({
    path: `/picture/${picture.id}`,
  })
}
// 编辑
const handleEdit = (picture: API.PictureVO, e: Event) => {
  e.stopPropagation()
  router.push({
    path: '/addPicture',
    query: {
      id: picture.id,
      spaceId: picture.spaceId,
    },
  })
}

// 删除
const handleDelete = async (picture: API.PictureVO, e: Event) => {
  e.stopPropagation()
  const id = picture.id
  if (!id) {
    return
  }
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 让外层刷新
    props?.onReload?.()
  } else {
    message.error('删除失败')
  }
}
</script>

<template>
  <!-- 图片列表 -->
  <a-list
    :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }"
    :data-source="props.dataList"
    :loading="props.loading"
  >
    <template #renderItem="{ item: picture }">
      <a-list-item style="padding: 0">
        <!-- 单张图片 -->
        <a-card hoverable @click="handleClickPicture(picture)">
          <template #cover>
            <img
              style="height: 180px; object-fit: cover"
              :alt="picture.name"
              :src="picture.thumbnailUrl ?? picture.url"
            />
            <!-- 控制是否要优先显示缩略图 -->
          </template>
          <a-card-meta :title="picture.name">
            <template #description>
              <a-flex>
                <a-tag color="green">
                  {{ picture.category ?? '默认' }}
                </a-tag>
                <a-tag v-for="tag in picture.tags" :key="tag">
                  {{ tag }}
                </a-tag>
              </a-flex>
            </template>
          </a-card-meta>
          <template v-if="showOp" #actions>
            <a-space @click="(e: Event) => handleEdit(picture, e)">
              <edit-outlined />
              编辑
            </a-space>
            <a-space @click="(e: Event) => handleDelete(picture, e)">
              <delete-outlined />
              删除
            </a-space>
          </template>
        </a-card>
      </a-list-item>
    </template>
  </a-list>
</template>

<style scoped></style>
